package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplus.model.domain.*;
import com.example.mybatisplus.model.dto.RepairForm;
import com.example.mybatisplus.model.dto.StudentStudyForm;
import com.example.mybatisplus.service.*;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 *  前端控制器
 *
 *
 * @author zzy
 * @since 2024-06-24
 * @version v1.0
 */
@RestController
@RequestMapping("/api/student")
public class StudentController {

    private final Logger logger = LoggerFactory.getLogger( StudentController.class );

    @Autowired
    private StudentService studentService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private AdjustDormitoryService adjustDormitoryService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private RatingTableService ratingTableService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        Student  student =  studentService.getById(id);
        return JsonResponse.success(student);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        studentService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateStudent(Student  student) throws Exception {
        studentService.updateById(student);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建Student
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(Student  student) throws Exception {
        studentService.save(student);
        return JsonResponse.success(null);
    }

    @GetMapping("/selectMajorNameAndCollegeNameByStudentID")
    public JsonResponse selectMajorNameAndCollegeNameByStudentID(Long StudentID){
        StudentStudyForm studentStudyForm = studentService.selectMajorNameAndCollegeNameByStudentID(StudentID);
        return JsonResponse.success(studentStudyForm);
    }
    @Transactional
    @PostMapping("/unCheckRoom")
    public JsonResponse unCheckRoom(@RequestBody Student student){
        QueryWrapper<AdjustDormitory> wrapper = new QueryWrapper<AdjustDormitory>();
        wrapper.ne("state", "已完成").eq("student", student.getId());
        List<AdjustDormitory> list = adjustDormitoryService.list(wrapper);
        if(list.size()!=0){
            return JsonResponse.failure("There are some transaction that have not finished.");
        }
        boolean b = adjustDormitoryService.save(new AdjustDormitory().
                setModifiedTime(LocalDateTime.now()).
                setCreatedTime(LocalDateTime.now()).
                setIsDeleted(0).
                setStudent(student.getId()).
                setState("处理中").
                setOutRoom(student.getRoom())
        );
        if(b)return JsonResponse.success(b,"Uncheck success.");
        else return JsonResponse.failure("Fail in check");
    }

    @PostMapping("/handleInDorm")
    public JsonResponse handleInDorm(Long StudentID){
        QueryWrapper<AdjustDormitory> wrapper = new QueryWrapper<AdjustDormitory>();
        wrapper.ne("state", "已完成").eq("student", StudentID);
        List<AdjustDormitory> list = adjustDormitoryService.list(wrapper);
        if(list.size()!=0){
            return JsonResponse.failure("There are some transaction that have not finished.");
        }
        boolean b = adjustDormitoryService.save(new AdjustDormitory().
                setModifiedTime(LocalDateTime.now()).
                setCreatedTime(LocalDateTime.now()).
                setIsDeleted(0).
                setStudent(StudentID).
                setState("处理中")
        );

        if(b)return JsonResponse.success("Uncheck success.");
        else return JsonResponse.failure("Fail in check");
    }

    @GetMapping("/selectBuildingsByAreaID")
    public JsonResponse selectBuildingsByAreaID(Long AreaID){
        QueryWrapper<Building> wrapper = new QueryWrapper<Building>()
                .eq("area",AreaID);
        List<Building> buildingList = buildingService.list(wrapper);
        return JsonResponse.success(buildingList);
    }
    @GetMapping("selectRoomsByBuildingID")
    public JsonResponse selectRoomsByBuildingID(Long BuildingID){
        QueryWrapper<Room> wrapper = new QueryWrapper<Room>()
                .eq("building",BuildingID);
        List<Room> list = roomService.list(wrapper);
        return JsonResponse.success(list);
    }

    @GetMapping("addAdjustRecord")
    public JsonResponse addAdjustRecord(Long StudentID, Long InRoomID, Long OutRoomID){
        QueryWrapper<AdjustDormitory> wrapper = new QueryWrapper<AdjustDormitory>();
        wrapper.ne("state", "已完成").eq("student", StudentID);
        List<AdjustDormitory> list = adjustDormitoryService.list(wrapper);
        if(list.size()!=0){
            return JsonResponse.failure("There are some transaction that have not finished.");
        }
        QueryWrapper<Room> wrapper1 = new QueryWrapper<Room>();
        wrapper1.eq("id",InRoomID);
        Long inBuildingID = roomService.getOne(wrapper1).getBuilding();
        AdjustDormitory adjustDormitory = new AdjustDormitory()
                .setStudent(StudentID)
                .setInRoom(InRoomID)
                .setOutRoom(OutRoomID)
                .setCreatedTime(LocalDateTime.now())
                .setModifiedTime(LocalDateTime.now())
                .setInBuilding(inBuildingID)
                .setIsDeleted(0)
                .setState("处理中");
        Boolean b = adjustDormitoryService.save(adjustDormitory);
        if(b)return JsonResponse.success("addAdjustRecord success.");
        else return JsonResponse.failure("Fail in addAdjustRecord");
    }
    @GetMapping("/getRating")
    JsonResponse getRating(Long RoomID){
        QueryWrapper<RatingTable> wrapper = new QueryWrapper<RatingTable>();
        wrapper.eq("room", RoomID).orderByDesc("rating_time");
        List<RatingTable> res = ratingTableService.list(wrapper);
        if(res.size()==0){
            return JsonResponse.failure(String.format("Room %l is not existed.",RoomID));
        }
        else return JsonResponse.success(res.get(0).getGrade());

    }
    @PostMapping("/getIndisciplineTable")
    public JsonResponse getIndisciplineTable(@RequestBody Dot dot){
        List<Indiscipline> indisciplineList = studentService.getIndisciplineTable(dot);
        int start = (dot.getPageNo()-1)*dot.getPageSize();
        int end = start+dot.getPageSize();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", indisciplineList.size());
        indisciplineList = indisciplineList.subList(start, Math.min(end,indisciplineList.size()));
        return JsonResponse.success(indisciplineList, "Success").setOtherData(map);
    }
    @PostMapping("/subRepair")
    public JsonResponse subRepair(String StudentID,String reason){
        boolean b = studentService.subRepair(Long.parseLong(StudentID),reason);
        if(b){
            return JsonResponse.success("Success");
        } else {
            return JsonResponse.failure("Fail");
        }
    }
    @PostMapping("/getRepairTable")
    public JsonResponse getRepairTable(@RequestBody Dot dot){
        dot.getData().put("student", Long.parseLong((String)dot.getData().get("student")));
        List<RepairForm> repairs = studentService.getRepairTable(dot);
        int start = (dot.getPageNo()-1)*dot.getPageSize();
        int end = start+dot.getPageSize();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", repairs.size());
        repairs = repairs.subList(start, Math.min(end,repairs.size()));
        return JsonResponse.success(repairs, "Success").setOtherData(map);
    }
}

